// 创建音频上下文
const audioContext = new (window.AudioContext || window.webkitAudioContext)();

// 创建MediaSource对象
const mediaSource = new MediaSource();

// 创建音频元素
const audioElement = new Audio();
audioElement.src = URL.createObjectURL(mediaSource);

// 连接音频元素和音频上下文
// const source = audioContext.createMediaElementSource(audioElement);
const source = audioContext.createMediaStreamDestination(audioElement);

source.connect(audioContext.destination);


// 创建SourceBuffer对象

let sourceBuffer;

// 监听MediaSource的sourceopen事件
mediaSource.addEventListener('sourceopen', () => {
  sourceBuffer = mediaSource.addSourceBuffer('audio/wav; codecs="opus"');
  // 监听sourceBuffer的updateend事件
  sourceBuffer.addEventListener('updateend', () => {
  // 如果sourceBuffer中有数据，则开始播放音频
    if (!sourceBuffer.updating && mediaSource.readyState === 'open') {
      mediaSource.endOfStream();
      audioElement.play();
    }
  });

});


// 接收音频数据并追加到sourceBuffer
function receiveAudioData(audioData) {
  // console.log(audioData);
  sourceBuffer.appendBuffer(audioData);
}



export { receiveAudioData };